import json
import base64
import os
import time
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614 import asr_client, models
import wave
import shutil
from wavTools import get_ms_part_wav,get_minute_part_wav
#音频切片，获取部分音频 分钟:秒数  时间样式："12:35"   get_minute_part_wav


SecretId = "AKIDlMincGdjY6NN6ZmiNmulLegS4PTHo43l"
SecretKey = "SdYCZfU2JK4WidGdjY6NM5YkeHdjZHju"
IS_ONLINE=False
STORAGE_PATH="/Users/leslie/PycharmProjects/python_wav/result"
ORINGIN_DIR="/Users/leslie/PycharmProjects/python_wav/audio"
ORINGIN_TEST_DIR="/Users/leslie/PycharmProjects/python_wav/test"

def create_task(file_path):
    if IS_ONLINE:
        try:
            cred = credential.Credential(SecretId, SecretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "asr.tencentcloudapi.com"
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = asr_client.AsrClient(cred, "", clientProfile)

            req = models.CreateRecTaskRequest()

            # file_path="/Users/leslie/PycharmProjects/python_wav/audio/0A0EA32A-3640-4A70-880E-38509736E111.wav"

            params = {
                "SpeakerNumber": 2,
                "EngineModelType": "8k_zh",
                "SpeakerDiarization": 1,
                "ChannelNum": 1,
                "ResTextFormat": 0,
                "SourceType": 0,
                "Url": file_path
            }
            req.from_json_string(json.dumps(params))

            resp = client.CreateRecTask(req)
            json_ = resp.to_json_string(indent=2)
            resp_dic = json.loads(json_)
            print(resp_dic)
            return dict(resp_dic)["Data"]["TaskId"]
            # print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)
    else:
        try:
            cred = credential.Credential(SecretId, SecretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "asr.tencentcloudapi.com"
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = asr_client.AsrClient(cred, "", clientProfile)

            req = models.CreateRecTaskRequest()

            #file_path="/Users/leslie/PycharmProjects/python_wav/audio/0A0EA32A-3640-4A70-880E-38509736E111.wav"

            with open(file_path, 'rb') as f:
                data = f.read()
            base64Wav = base64.b64encode(data).decode()

            params = {
                "SpeakerNumber": 2,
                "EngineModelType": "8k_zh",
                "SpeakerDiarization": 1,
                "ChannelNum": 1,
                "ResTextFormat": 0,
                "SourceType": 1,
                "Data":base64Wav
            }
            req.from_json_string(json.dumps(params))

            resp = client.CreateRecTask(req)
            json_=resp.to_json_string(indent=2)
            resp_dic=json.loads(json_)
            #print(resp_dic)
            return dict(resp_dic)["Data"]["TaskId"]
            #print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)

def query_result(task_id):

    try:
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = asr_client.AsrClient(cred, "", clientProfile)

        req = models.DescribeTaskStatusRequest()
        params = {
        "TaskId":task_id
        }
        req.from_json_string(json.dumps(params))
        resp = client.DescribeTaskStatus(req)
        #print(resp)
        json_ = resp.to_json_string(indent=2)
        resp_dic = json.loads(json_)
        #print(resp_dic)
        return resp_dic["Data"]["Result"]
        #print(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)

def storage_list(storage_path,obj_list):
    fileObject = open(storage_path, 'w')
    for ip in obj_list:
        fileObject.write(ip)
        fileObject.write('\n')
    fileObject.close()


def process(dir):

    processed_file = []
    checkpoint_task_txt="checkpoint_task_list"+str(time.time())+".txt"
    print(checkpoint_task_txt)
    file_object = open(checkpoint_task_txt, 'w')
    file_error_object = open(checkpoint_task_txt, 'w')
    process_dic={}
    try:
        for file in os.listdir(dir):
            #print(file)

            file_split = os.path.splitext(file)
            if (file_split[1] == ".wav"):
                validate_size(file)
                file_path = os.path.join(ORINGIN_DIR, file)
                task_id = create_task(file_path)
                if task_id is not None:
                    #print(task_id)
                    file_object.write(file)
                    file_object.write(':')
                    file_object.write(str(task_id))
                    file_object.write('\n')
                    processed_file.append(file)
                    process_dic[file]=task_id
                    print(file+":"+str(task_id))
                else:
                    file_error_object.write(file)
                    file_error_object.write('\n')
                    processed_file.append(file)
        print(process_dic)
        storage_list("processed_list.txt", processed_file)
        file_object.close()
        file_error_object.close()
    except:
        storage_list("processed_list.txt", processed_file)
        print(process_dic)
        file_object.close()

def get_time_split_list(result):

    time_split_point_list=[]
    result_list=str.split(result)
    init=0
    for item in result_list:
        if init%2==0:
            init += 1
            time_split_point_list.append(item)
        else:
            init += 1
            pass
    return time_split_point_list
    #print(time_split_point_list)

def get_split_time(result):
    time_split = get_time_split_list(result)
    speaker_class_list_0 = []
    speaker_class_list_1 = []
    for i in time_split:
        time = i[1:-1].split(",")
        print("time:",time)
        print("i:",i)
        try:
            speaker_class = int(time[2])
            if speaker_class == 0:
                speaker_class_list_0.append(time[:-1])
            if speaker_class == 1:
                speaker_class_list_1.append(time[:-1])
        except:
            pass
        # transform_list.append(j)
    return speaker_class_list_0,speaker_class_list_1
    # print(speaker_class_list_0)
    # print(speaker_class_list_1)


def get_part_audio(file_name_format, time_list,class_num,part_num):

    file_path=os.path.join(ORINGIN_DIR,file_name_format)
    a1_min_mil = float(time_list[0][:-1].split(":")[0]) * 1000 * 60
    a1_sec_mil = float(time_list[0][:-1].split(":")[1]) * 1000
    a2_min_mil = float(time_list[1][:-1].split(":")[0]) * 1000 * 60
    a2_sec_mil = float(time_list[1][:-1].split(":")[1]) * 1000
    start_mil = a1_min_mil + a1_sec_mil
    end_mil = a2_min_mil + a2_sec_mil
    storage_file_name = os.path.splitext(file_name_format)[0]+"_"+str(class_num)+"_"+str(part_num)+".wav"
    out_name = os.path.splitext(file_name_format)[0] + "_" + str(class_num) + ".wav"
    dir_path=os.path.join(STORAGE_PATH,file_name_format)
    get_ms_part_wav(file_path, start_mil, end_mil,storage_file_name)
    #print(storage_file_name,dir_path)
    shutil.move(storage_file_name,dir_path)
    part_file_path=os.path.join(dir_path,storage_file_name)
    concat_file_path=os.path.join(dir_path,out_name)

    return part_file_path,concat_file_path



def concat_audio(input_audio_0, input_audio_1,out_path):
    infiles = [input_audio_0, input_audio_1]
    data = []
    for infile in infiles:
        w = wave.open(infile, 'rb')
        data.append([w.getparams(), w.readframes(w.getnframes())])
        w.close()
    os.remove(input_audio_0)
    os.remove(input_audio_1)
    try:
        os.remove(out_path)
    except:
        pass
    output = wave.open(out_path, 'wb')
    output.setparams(data[0][0])
    output.writeframes(data[0][1])
    output.writeframes(data[1][1])
    output.close()

#存储翻译的文本至指定文件
def str_to_txt(filename, speaker_class,contents):
    save_path=os.path.join(STORAGE_PATH,filename)
    save_name=filename+"_"+str(speaker_class)+".txt"
    fh = open(save_name, 'w')
    fh.write(contents)
    #print(save_path)
    shutil.move(save_name,save_path)
    fh.close()

def process_one_wav(file_name,class_num,time_list):
    storage_dir=os.path.join( STORAGE_PATH,file_name )
    #print(storage_dir)
    try:
        os.mkdir(storage_dir)
    except:
        pass
    len_time_list=len(time_list)
    #print(len_time_list==1)
    if len_time_list==0:
        pass
    if len_time_list==1:
        get_part_audio(file_name,time_list[0],class_num,class_num)
    if len_time_list==2:
        part_file_path_0 ,concat_file_path = get_part_audio(file_name, time_list[0], class_num, 0)
        part_file_path_1,concat_file_path = get_part_audio(file_name, time_list[1], class_num, 1)
        concat_audio(part_file_path_0, part_file_path_1,concat_file_path)
    if len_time_list > 2:
        #print("else>>>>")
        split_time_num=len(time_list)
        part_file_path_0, concat_file_path = get_part_audio(file_name, time_list[0], class_num, 0)
        part_file_path_1, concat_file_path = get_part_audio(file_name, time_list[1], class_num, 1)
        ##print(concat_file_path)
        concat_audio(part_file_path_0, part_file_path_1, concat_file_path)
        for time_num in range(split_time_num):
            if time_num<2:
                pass
            else:
                part_file_path, concat_file_path = get_part_audio(file_name, time_list[time_num], class_num, time_num)
                concat_audio(part_file_path, concat_file_path, concat_file_path)



def get_txt_split_list(result):

    time_split_point_list=[]

    result_list=str.split(result)

    for item in result_list:

            time_split_point_list.append(item)

    return time_split_point_list
    #print(time_split_point_list

def save_txt(result,file_name):

    txt_split = get_txt_split_list(result)
    #print(txt_split)
    class_txt_0 = []
    class_txt_1 = []
    init = 0
    for i in txt_split:
        if init % 2 == 0:
            init += 1
            #print(i)
            class_num = int(i[-2])
            if class_num == 0:
                class_txt_0.append(i + ":" + txt_split[init])
            if class_num == 1:
                class_txt_1.append(i + ":" + txt_split[init])
        else:
            init += 1
    #print(">>>>>>>")
    #print(class_txt_0,class_txt_1)
    str_to_txt(file_name ,0, str(class_txt_0))
    str_to_txt(file_name ,1, str(class_txt_1))



def process_one_file(file_name,task_id):
    result=query_result(task_id)
    #print(result)
    speaker_class_list_0,speaker_class_list_1=get_split_time(result)
    process_one_wav(file_name, 0, speaker_class_list_0)
    process_one_wav(file_name, 1, speaker_class_list_1)
    save_txt(result, file_name)

def get_file_size(filePath):
    fsize = os.path.getsize(filePath)
    fsize = fsize / float(1024 * 1024)
    return round(fsize, 2)

def validate_size(file):
    file_path = os.path.join(ORINGIN_DIR, file)
    size = get_file_size(file_path)
    print("%s的大小:%f MB"%(file,size))
    if size >= 5:
        get_minute_part_wav(file_path, "0:0", "4:30", file)
        #print(get_file_size(file))
        os.remove(file_path)
        shutil.move(file, ORINGIN_DIR)

def oooooooo():
    faild=[]

    f = open("result.txt")  # 返回一个文件对象
    line = f.readline()  # 调用文件的 readline()方法
    state=0
    a=[]
    while line:
        if state%2==0:
            a.append(line)
        line = f.readline()
        state=state+1
    f.close()
    b=a[:-1]
    for i in b:
        print(i)
        file_name=i[:-12]
        task_id=int(i[-11:-1])
        try:
            process_one_file(file_name,task_id)
        except:
            faild.append(file_name)
    return faild


if __name__ == '__main__':
    #a="/Users/leslie/PycharmProjects/python_wav/test/0A0EA32A-3640-4A70-880E-38509736E111.wav"
    #a="/Users/leslie/PycharmProjects/python_wav/test/FF91F3A2-EEFA-43BC-9904-03F15B812AA6.wav"
    #获取文件夹，上传文件
    dir_="processed"

    process(dir_)






